<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="500px">
			<el-form ref="roleDialogFormRef" :model="state.ruleForm" size="default" label-width="120px" v-loading="state.dataLoading" label-position="left" style="min-height: 50px;">
				<el-form-item label="所属角色" prop="roleIdList" >
					<el-checkbox-group v-model="state.ruleForm.roleIdList" size="default" class="check-box">
						<el-checkbox v-for="(item,index) in state.roleList" :key="index" :label="item.id"   >{{ item.name }}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" :loading="state.btnLoading" @click="onSubmit" size="default">确认</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="systemRoleDialog">
import { systemApi } from '/@/api/system'
import { ElMessage } from 'element-plus';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const roleDialogFormRef = ref();
const state = reactive({
	ruleForm: {
		roleIdList : []
	},
	dialog: {
		isShowDialog: false,
		title: '修改角色',
		submitTxt: '',
	},
	userDetail: null,
	dataLoading:false,
	roleList: [],
	btnLoading: false
});

// 打开弹窗
const openDialog = (row) => {
	state.userDetail = row;
	const roleList = []
	if(row.role.length){
		row.role.forEach(item => {
			roleList.push(item.id)
		})
	}
	state.ruleForm.roleIdList = roleList
	state.dialog.isShowDialog = true;
	state.dataLoading = true
	systemApi().simpleRoleList().then(res=>{
		state.dataLoading = false
		state.roleList = res.data
	}).catch(() => {
		state.dataLoading = false
	})
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	state.btnLoading = true
	const apiData = {
		uid: state.userDetail.id,
		role_ids: state.ruleForm.roleIdList
	}
	systemApi().changeUserRole(apiData).then(res => {
		state.btnLoading = false
		ElMessage.success('操作成功');
		closeDialog();
		emit('refresh');
	}).catch(() => {
		state.btnLoading = false
		closeDialog();
		emit('refresh');
	})
	
};


// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">

</style>
